package com.tdtxdcxm.ruralcommunity.slice;

import com.tdtxdcxm.ruralcommunity.ResourceTable;
import com.tdtxdcxm.ruralcommunity.appruntime.DataCenterControl;
import com.tdtxdcxm.ruralcommunity.httpmanagers.ThreadPoolUtil;
import com.tdtxdcxm.ruralcommunity.items.LCArryListNormalItem;
import com.tdtxdcxm.ruralcommunity.myutils.MyTools;
import com.tdtxdcxm.ruralcommunity.providers.LCProviderForNormal;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.net.NetStatusCallback;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class PeopleListSlice extends AbilitySlice {
    private Button usercontent_backbut;
    private ListContainer usercontent_lc;

    /*<****************http搜索用户数据区域*****************/
    public void UpDataSearchUserInfo(String username,String objectname){
        NetManager main_toplistnetmanger = NetManager.getInstance(this.getContext());
        if (!main_toplistnetmanger.hasDefaultNet()) {
            return;
        }
        ThreadPoolUtil.submit(() -> {
            NetHandle thenetHandle = main_toplistnetmanger.getDefaultNet();
            NetStatusCallback netStatusCallback = new NetStatusCallback() {};
            HttpURLConnection httpURLConnection = null;

            String urlString = DataCenterControl.serverIpWithPort + "searchuser/?";
            try {
                URL url = new URL(urlString);

                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                URLConnection urlConnection = thenetHandle.openConnection(url, java.net.Proxy.NO_PROXY);
                if (urlConnection instanceof HttpURLConnection) {
                    httpURLConnection = (HttpURLConnection) urlConnection;

                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);

                    StringBuilder stringBuilder = new StringBuilder();

                    stringBuilder.append("username=");
                    stringBuilder.append(username);
                    stringBuilder.append("&objectname=");
                    stringBuilder.append(objectname);


                    byte[] b = stringBuilder.toString().getBytes();
                    httpURLConnection.getOutputStream().write(b);

                    try {
                        httpURLConnection.connect();
                    } catch (IOException e) {}
                    outputStream.flush();


                    InputStream inputStream = null;
                    try {
                        inputStream = urlConnection.getInputStream();
                        byte[] cache = new byte[2 * 1024];
                        int len = inputStream.read(cache);
                        while (len != -1) {
                            outputStream.write(cache, 0, len);
                            len = inputStream.read(cache);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String result = "";
                    result = outputStream.toString();
                    if(result.startsWith("OK")){
                        //搜索成功
                        String finalResult = result;
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                DataCenterControl.people_listcontainer_list.clear();
                                DataCenterControl.people_listcontainer_list.add(new LCArryListNormalItem(finalResult.substring(3)));
                                if(DataCenterControl.peopleListContainerProvider != null){
                                    DataCenterControl.peopleListContainerProvider.notifyDataChanged();
                                }
                            }
                        });
                    }
                    else{
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                MyTools.toastShow("搜索为空！", PeopleListSlice.this.getContext());
                            }
                        });

                    }
                }
            } catch (IOException e) {

            } finally {
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            }
        });

    }
    /******************http搜索用户数据区域***************>*/

    private void initListContainer(ListContainer listContainer,String listContainerName,AbilitySlice slice){
        if(listContainer == null){
            return;
        }
        listContainer.setName(listContainerName);
        LCProviderForNormal lcProviderForNormal = new LCProviderForNormal(DataCenterControl.people_listcontainer_list,this);
        if(lcProviderForNormal != null){
            listContainer.setItemProvider(lcProviderForNormal);
            DataCenterControl.peopleListContainerProvider = lcProviderForNormal;
        }

        listContainer.setItemLongClickedListener(new ListContainer.ItemLongClickedListener() {
            @Override
            public boolean onItemLongClicked(ListContainer listContainer, Component component, int i, long l) {
                DirectionalLayout directionalLayout= ((DirectionalLayout)component);
                Text text = (Text)directionalLayout.getComponentAt(0);
                if(text.getText().endsWith("关注")){

                }
                else if(text.getText().endsWith("已关注")){

                }
                return true;
            }
        });
    }

    private void initPLSComponents(){
        usercontent_backbut = (Button) findComponentById(ResourceTable.Id_usercontent_backbut);
        usercontent_lc = (ListContainer) findComponentById(ResourceTable.Id_usercontent_lc);

        usercontent_backbut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                DataCenterControl.people_listcontainer_list.clear();
                terminate();
            }
        });
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_usercontent_item_listcontainer);
        initPLSComponents();
        initListContainer(usercontent_lc,"peoplelc",this);
        UpDataSearchUserInfo(DataCenterControl.userName,intent.getStringParam("objectname"));
    }

    @Override
    protected void onActive() {
        super.onActive();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onBackground() {
        super.onBackground();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}
